package com.blank.shop.seata.storage;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.blank.shop.seata.ShopAlibabaSeataApplication;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <br/>Date 2021/8/30
 * <br/>Time 16:09:31
 *
 * @author _blank
 */
@Profile({ShopAlibabaSeataApplication.PROFILE_STORAGE})
@RestController
public class StorageController {

    public static final String UPDATE_SQL = "UPDATE t_storage SET used=used+?, residue=residue-? WHERE product_id=?";

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 库存扣减
     *
     * @param productId 产品id
     * @param count     数量
     * @return org.springframework.http.ResponseEntity
     */
    @PostMapping(path = {"storage-decrease"})
    public ResponseEntity<String> decrease(Long productId, Integer count) {
        try {
            DynamicDataSourceContextHolder.push(ShopAlibabaSeataApplication.DS_STORAGE);
            final int affectedRows = this.jdbcTemplate.update(UPDATE_SQL
                    , count
                    , count
                    , productId
            );
            return ResponseEntity.ok("storage-decrease-ok-" + affectedRows);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
